import React, { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { setEditId, setTodoName } from '../../redux/store'
import './Item.css'
export default function Item({ todo: { id, todoName, isDone } }) {
  // 定义状态tN,控制编辑文本框的值
  const [tN, setTN] = useState('')
  // 获取dispatch
  const dispatch = useDispatch()
  // 获取editId的值
  const editId = useSelector((state) => {
    return state.todo.editId
  })
  return (
    <li>
      {editId !== id ? (
        <label>
          <input type="checkbox" checked={isDone} onChange={() => {}} />
          <span className={isDone ? 'done' : ''}>{todoName}</span>
        </label>
      ) : (
        <input
          type="text"
          value={tN}
          onChange={(e) => {
            setTN(e.target.value.trim())
          }}
          onKeyUp={(e) => {
            if (e.key !== 'Enter' || !tN) return
            // 按下回车键,修改当前任务的任务名
            dispatch(setTodoName({ id, todoName: tN }))
            // 将editId改为undefined
            dispatch(setEditId(undefined))
          }}
        />
      )}
      <button className="btn btn-danger">删除</button>
      <button
        className="btn btn-edit"
        onClick={() => {
          // 修改editId的值
          dispatch(setEditId(editId !== id ? id : undefined))
          // 修改tN,让当前任务名渲染在编辑文本框中
          setTN(todoName)
        }}
      >
        {editId !== id ? '编辑' : '取消'}
      </button>
    </li>
  )
}
